<?php
/**
 * JWT相关业务
 *
 * @author  
 * @time 2024-01-18 12:24:50
 */

namespace App\Services;

use Illuminate\Support\Facades\Log;
use Lcobucci\JWT\Parser;
use DateTimeImmutable;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Encoding\CannotDecodeContent;
use Lcobucci\JWT\Token\InvalidTokenStructure;
use Lcobucci\JWT\Token\UnsupportedHeaderFound;

class AuthToken
{
    /**
     * 生成Token
     *
     * @param $userId
     * @return string
     * @author  
     */
    public static function getJwt($userId)
    {
        $signingKey = InMemory::plainText(config('auth.jwt_secret'));

        $now = new DateTimeImmutable();
        $token = (new Builder())
            // todo 了解issuedBy是否需要配置
//            ->issuedBy('http://example.com')
            ->withHeader('key', config('auth.jwt_key'))
            ->withClaim('user_id', $userId)
            ->expiresAt($now->modify('+7 day'))
            ->getToken(new Sha256(), $signingKey);
        return $token->toString();
    }

    /**
     * 检验jwt Token
     *
     * @param $token
     * @return false
     * @author  
     */
    public static function checkJwt($token)
    {
        try {
            $token = (new Parser())->parse($token);
        } catch (CannotDecodeContent|InvalidTokenStructure|UnsupportedHeaderFound $e) {
            Log::error('checkJet error:' . $e->getMessage());
            return false;
        }

        if ($token->isExpired()) {
            return false;
        }

        if ($token->headers()->get("key") != config('auth.jwt_key')) {
            return false;
        }

        return $token->claims()->get("user_id");
    }


}